import React, { useState, useEffect } from 'react';
import { useAuth } from '@/hooks/useAuth';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { CustomTitlebar } from '@/components/CustomTitlebar';
import PasswordGeneratorWindow from '@/components/PasswordGeneratorWindow';

interface PasswordStrength {
  score: number;
  feedback: string;
  isValid: boolean;
}

interface PasswordSetupProps {
  onSuccess?: () => void;
}

const PasswordSetup: React.FC<PasswordSetupProps> = ({ onSuccess }) => {
  const { setMasterPassword, verifyMasterPassword, isLoading, error, clearError } = useAuth();
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState<PasswordStrength>({
    score: 0,
    feedback: '',
    isValid: false,
  });
  const [formErrors, setFormErrors] = useState<{
    password?: string;
    confirmPassword?: string;
  }>({});
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" | "info" } | null>(null);
  const [isPasswordGeneratorOpen, setIsPasswordGeneratorOpen] = useState(false);

  // Check password strength
  const checkPasswordStrength = (pwd: string): PasswordStrength => {
    let score = 0;
    let feedback = '';
    
    if (pwd.length < 8) {
      feedback = '密码长度至少需要8个字符';
      return { score: 0, feedback, isValid: false };
    }
    score += 1;
    
    if (pwd.length >= 12) {
      score += 1;
    }
    
    if (/[a-z]/.test(pwd)) {
      score += 1;
    } else {
      feedback += '需要包含小写字母。';
    }
    
    if (/[A-Z]/.test(pwd)) {
      score += 1;
    } else {
      feedback += '需要包含大写字母。';
    }
    
    if (/[0-9]/.test(pwd)) {
      score += 1;
    } else {
      feedback += '需要包含数字。';
    }
    
    if (/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(pwd)) {
      score += 1;
    } else {
      feedback += '需要包含特殊字符。';
    }
    
    const isValid = score >= 3;
    
    if (isValid) {
      if (score >= 5) {
        feedback = '密码强度优秀';
      } else {
        feedback = '密码强度良好';
      }
    } else {
      feedback = '密码强度较弱，请按照要求设置';
    }
    
    return { score, feedback, isValid };
  };

  // Update password strength when password changes
  useEffect(() => {
    if (password) {
      const strength = checkPasswordStrength(password);
      setPasswordStrength(strength);
    } else {
      setPasswordStrength({ score: 0, feedback: '', isValid: false });
    }
  }, [password]);

  // Clear errors when user starts typing
  useEffect(() => {
    if (error) {
      clearError();
    }
  }, [password, confirmPassword, error, clearError]);

  const validateForm = () => {
    const errors: { password?: string; confirmPassword?: string } = {};
    
    if (!password) {
      errors.password = '请输入密码';
    } else if (!passwordStrength.isValid) {
      errors.password = passwordStrength.feedback;
    }
    
    if (!confirmPassword) {
      errors.confirmPassword = '请确认密码';
    } else if (password !== confirmPassword) {
      errors.confirmPassword = '两次输入的密码不一致';
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    const success = await setMasterPassword(password);
    if (success) {
      // Password set successfully, verify it to cache in backend and authenticate
      await verifyMasterPassword(password);
      setPassword('');
      setConfirmPassword('');
      // Call success callback if provided
      if (onSuccess) {
        onSuccess();
      }
    }
  };

  const getStrengthColor = (score: number) => {
    if (score >= 5) return 'text-green-500';
    if (score >= 3) return 'text-green-500';
    return 'text-red-500';
  };

  const getStrengthBarColor = (score: number) => {
    if (score >= 5) return 'bg-green-500';
    if (score >= 3) return 'bg-green-500';
    return 'bg-red-500';
  };

  return (
    <div className="flex flex-col">
      {/* Only show titlebar if not in modal mode */}
      {!onSuccess && (
        <CustomTitlebar
          onSettingsClick={() => setToast({ message: "Settings clicked", type: "info" })}
          onInfoClick={() => setToast({ message: "密码管理器 v1.0.0", type: "info" })}
          onPasswordGeneratorClick={() => setIsPasswordGeneratorOpen(true)}
        />
      )}
      
      {/* Main Content */}
      <div className={`${onSuccess ? 'p-6' : 'h-screen flex items-center justify-center bg-background p-4'}`}>
        <div className={`w-full ${onSuccess ? '' : 'max-w-md'} space-y-6`}>
        <div className="text-center">
          <h1 className="text-2xl font-bold text-foreground mb-2">
            设置主密码
          </h1>
          <p className="text-muted-foreground">
            请设置一个强密码来保护您的密码管理器
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="password">密码</Label>
            <div className="relative">
              <Input
                id="password"
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="请输入密码"
                className={formErrors.password ? 'border-red-500' : ''}
                disabled={isLoading}
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                onClick={() => setShowPassword(!showPassword)}
                disabled={isLoading}
              >
                {showPassword ? '隐藏' : '显示'}
              </Button>
            </div>
            {formErrors.password && (
              <p className="text-sm text-red-500">{formErrors.password}</p>
            )}
          </div>

          {/* Password Strength Indicator */}
          {password && (
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <div className="flex-1 bg-gray-200 rounded-full h-2">
                  <div
                    className={`h-2 rounded-full transition-all duration-300 ${getStrengthBarColor(passwordStrength.score)}`}
                    style={{ width: `${(passwordStrength.score / 6) * 100}%` }}
                  />
                </div>
                <span className={`text-sm font-medium ${getStrengthColor(passwordStrength.score)}`}>
                  {passwordStrength.score}/6
                </span>
              </div>
              <p className={`text-sm ${getStrengthColor(passwordStrength.score)}`}>
                {passwordStrength.feedback}
              </p>
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="confirmPassword">确认密码</Label>
            <div className="relative">
              <Input
                id="confirmPassword"
                type={showConfirmPassword ? 'text' : 'password'}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                placeholder="请再次输入密码"
                className={formErrors.confirmPassword ? 'border-red-500' : ''}
                disabled={isLoading}
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                disabled={isLoading}
              >
                {showConfirmPassword ? '隐藏' : '显示'}
              </Button>
            </div>
            {formErrors.confirmPassword && (
              <p className="text-sm text-red-500">{formErrors.confirmPassword}</p>
            )}
          </div>

          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-sm text-red-600">{error}</p>
            </div>
          )}

          <Button
            type="submit"
            className="w-full"
            disabled={isLoading || !passwordStrength.isValid || password !== confirmPassword}
          >
            {isLoading ? '设置中...' : '设置密码'}
          </Button>
        </form>

        <div className="text-center text-sm text-muted-foreground">
          <p>密码要求：</p>
          <ul className="mt-2 space-y-1 text-xs">
            <li>• 至少8个字符</li>
            <li>• 包含大写和小写字母</li>
            <li>• 包含数字和特殊字符</li>
          </ul>
        </div>
        </div>
      </div>
      
      {/* Toast Container */}
      {toast && (
        <div className="fixed bottom-4 right-4 bg-background border border-border rounded-lg p-3 shadow-lg">
          <p className="text-sm">{toast.message}</p>
        </div>
      )}
      
      {/* Password Generator Window */}
      <PasswordGeneratorWindow
        isOpen={isPasswordGeneratorOpen}
        onClose={() => setIsPasswordGeneratorOpen(false)}
      />
    </div>
  );
};

export default PasswordSetup;
